from datetime import datetime
from typing import Any, Optional

from sqlalchemy.orm import Session

from app.db.session import get_db, db_close
from app.llama_index.session.livsm_session import MilvusVectorStoreSession, livsmSessions
from app.models import Document
from app.models.knowledge import DocumentStatus, KnowledgeBase

def knowledge_services_query_by_kb_id(
        kb_id:int,
        msg:str,
        db:Optional[Session]=None,
) -> str:
    """查询知识库"""
    _db=db
    if _db is None:
        _db = next(get_db())
    kb:KnowledgeBase = _db.query(KnowledgeBase).filter(
        KnowledgeBase.id == kb_id,
        ).first()
    db_close(_db)
    return knowledge_services_query_by_KnowledgeBase(kb,msg)

def knowledge_services_query_by_KnowledgeBase(
        kb:KnowledgeBase,
        msg:str
) -> str:
    """查询知识库"""
    session:MilvusVectorStoreSession=livsmSessions.get_session(
        kb_id=kb.id,
        dimensions=kb.dimensions,
        enable_sparse=kb.enable_sparse
    )
    return session.query(msg)

def knowledge_services_change_knowledge_doc_status(
        kb:KnowledgeBase,
        doc:Document,
        status:str
) -> bool:
    """
    Change knowledge doc status.

    return True 变更成功
    """
    mvss: MilvusVectorStoreSession = livsmSessions.get_session(
        kb_id=kb.id,
        dimensions=kb.dimensions,
        enable_sparse=kb.enable_sparse
    )
    doc.error_message=''
    #原状态为 待向量化
    if doc.status == DocumentStatus.DRAFT.value.value:
        doc.error_message=f'原状态为 {DocumentStatus.getValueLabelUseMsg(doc.status)} ，不能变更为任何状态'
        return False

    # 向量化中 -> 草稿
    if doc.status == DocumentStatus.PROCESSING.value.value:
        if status == DocumentStatus.DRAFT.value.value:
            #删除向量数据库对应记录
            mvss.delDoc(doc)
            doc.status = status
            doc.status_time = datetime.now()
            return True
        doc.error_message = f'状态为 {DocumentStatus.getValueLabelUseMsg(doc.status)} ，只能变更为 {DocumentStatus.DRAFT.get_value_label_use_msg()}'
        return False

    #向量化失败 -> 草稿
    if doc.status == DocumentStatus.PROCESSING_FAILED.value.value:
        if status != DocumentStatus.DRAFT.value.value:
            doc.error_message = f'状态为 {DocumentStatus.getValueLabelUseMsg(doc.status)} ，只能变更为 {DocumentStatus.DRAFT.get_value_label_use_msg()}'
            return False
        # 删除向量数据库对应记录
        mvss.delDoc(doc)
        doc.status = status
        doc.status_time = datetime.now()
        return True
    # 禁用 -> 草稿
    if doc.status == DocumentStatus.DISABLED.value.value:
        if status != DocumentStatus.DRAFT.value.value:
            doc.error_message = f'状态为 {DocumentStatus.getValueLabelUseMsg(doc.status)} ，只能变更为 {DocumentStatus.DRAFT.get_value_label_use_msg()}'
            return False
        doc.status = status
        doc.status_time = datetime.now()
        return True

    #关闭 -> 禁用
    if doc.status == DocumentStatus.CLOSED.value.value:
        if status == DocumentStatus.DISABLED.value.value:
            doc.error_message = f'状态 {DocumentStatus.DISABLED.get_value_label_use_msg()} 变更为 {DocumentStatus.DISABLED.get_value_label_use_msg()} 的逻辑未完成'
            #删除向量数据库对应记录
            mvss.delDoc(doc)
            doc.status = status
            doc.status_time = datetime.now()
            return True

        doc.error_message = f'原状态为 {DocumentStatus.getValueLabelUseMsg(doc.status)} ，只能变更为 {DocumentStatus.DISABLED.get_value_label_use_msg()}'
        return False
    # doc.
    return False
